<template>
	<view class="container">
		<!-- 账号管理区域 -->
		<view class="account-manager">
			<view class="account-header">
				<text class="account-title">账号管理</text>
				<button class="add-account-btn" @click="getWxLoginQrCode">添加新账号</button>
			</view>
			
			<!-- 账号列表 -->
			<view class="account-list">
				<view v-for="(account, index) in accounts" :key="index" 
					class="account-item" 
					:class="{ 'account-active': account.roleId === currentAccount?.roleId }">
					<view class="account-info">
						<text class="account-nickname">{{ account.nickname || '未设置昵称' }}</text>
						<text class="account-id">修仙ID: {{ account.roleId }}</text>
					</view>
					<view class="account-actions">
						<button class="account-btn" @click="switchAccount(account)">切换</button>
						<button class="account-btn delete" @click="deleteAccount(index)">删除</button>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 微信登录区域 -->
		<view class="wx-login-area" v-if="showLoginArea">
			<view class="wx-login-header">
				<button class="wx-login-btn" @click="getWxLoginQrCode">获取微信登录二维码</button>
				<button class="close-btn" @click="closeLoginArea">✕</button>
			</view>
			<image v-if="qrCodePath" class="qr-code" :src="qrCodePath" mode="aspectFit"></image>
			<text v-if="qrCodePath" class="qr-tip">请使用微信扫描二维码登录</text>
			<text v-if="scanStatus" class="scan-status">{{scanStatus}}</text>
			
			<!-- Token 显示区域
			<view v-if="chaojiToken" class="token-area">
				<view class="token-row">
					<text class="token-label">超级链接Token:</text>
					<input class="token-input" type="text" :value="chaojiToken" disabled />
					<button class="copy-btn" @click="copyToken('chaojiToken')">复制</button>
				</view>
			</view> -->
			
			<!-- <view v-if="chaowanToken" class="token-area">
				<view class="token-row">
					<text class="token-label">潮玩Token:</text>
					<input class="token-input" type="text" :value="chaowanToken" disabled />
					<button class="copy-btn" @click="copyToken('chaowanToken')">复制</button>
				</view>
				<view class="token-row" v-if="userId">
					<text class="token-label">用户ID:</text>
					<input class="token-input" type="text" :value="userId" disabled />
					<button class="copy-btn" @click="copyToken('userId')">复制</button>
				</view>
				<view class="token-row" v-if="roleId">
					<text class="token-label">修仙ID:</text>
					<input class="token-input" type="text" :value="roleId" disabled />
					<button class="copy-btn" @click="copyToken('roleId')">复制</button>
				</view>
			</view> -->
		</view>
	</view>
</template>

<script>
import { ref, onMounted, onUnmounted } from 'vue';

export default {
	components: {
		// 移除 AdBanner 组件注册
	},
	data() {
		return {
			title: '', // 删除默认标题
			qrCodePath: '',
			uuid: '',
			scanStatus: '',
			token: '',
			chaojiToken: '',
			chaowanToken: '',
			userId: '',  // 添加userId字段
			roleId: '',  // 添加roleId字段
			scanTimer: null,
			wxLoginParams: {
				appid: "wxa08b340057af146e", 
				bundleid: "com.caike.union", 
				scope: "snsapi_userinfo", 
				state: Math.random().toString(36).substring(2, 15),
				pass_ticket: ""
			},
			wxLoginHeaders: {
				"User-Agent": "Mozilla/5.0 (Linux; Android 9; PBBT00 Build/PPR1.180610.011; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/70.0.3538.110 Mobile Safari/537.36 MMWEBID/3625 MicroMessenger/7.0.17.1720(0x27001134) Process/tools WeChat/arm32 NetType/4G Language/zh_CN ABI/arm64", 
				"Accept": "*/*", 
				"Connection": "keep-alive",
				"Host": "open.weixin.qq.com"
			},
			isGettingQrCode: false,
			hasValidToken: false,
			accounts: [], // 存储所有账号
			currentAccount: null, // 当前选中的账号
			showLoginArea: false, // 控制登录区域的显示
			switchAccountTimer: null,
			deleteAccountTimer: null,
			addAccountTimer: null,
			getRoleIdTimer: null,
			hasShownLoginToast: false, // 添加标志位，确保提示只显示一次
		}
	},
	methods: {
		// 加载账号列表
		loadAccounts() {
			try {
				const savedAccounts = uni.getStorageSync('plunder_accounts') || [];
				this.accounts = savedAccounts;
				
				// 获取当前账号
				const currentAccountId = uni.getStorageSync('current_account_id');
				if (currentAccountId) {
					this.currentAccount = this.accounts.find(acc => acc.roleId === currentAccountId);
				} else if (this.accounts.length > 0) {
					this.currentAccount = this.accounts[0];
					uni.setStorageSync('current_account_id', this.currentAccount.roleId);
				}
				
				console.log('加载的账号列表:', this.accounts);
				console.log('当前账号:', this.currentAccount);
			} catch (e) {
				console.error('加载账号列表失败:', e);
				this.accounts = [];
			}
		},
		
		// 切换账号
		switchAccount(account) {
			if (this.currentAccount?.roleId === account.roleId) {
				uni.showToast({
					title: '当前已是该账号',
					icon: 'none'
				});
				return;
			}
			
			// 添加防抖，避免频繁切换
			if (this.switchAccountTimer) {
				clearTimeout(this.switchAccountTimer);
			}
			
			this.switchAccountTimer = setTimeout(() => {
				this.currentAccount = account;
				uni.setStorageSync('current_account_id', account.roleId);
				
				// 更新配置
				const config = {
					...uni.getStorageSync('plunder_config'),
					token: account.token,
					uid: account.uid,
					roleId: account.roleId,
					nickname: account.nickname
				};
				uni.setStorageSync('plunder_config', config);
				
				uni.showToast({
					title: '切换账号成功',
					icon: 'success'
				});
				
				// 使用 nextTick 确保状态更新后再触发事件
				this.$nextTick(() => {
					uni.$emit('account-switched', account);
				});
			}, 300); // 300ms 的防抖延迟
		},
		
		// 删除账号
		deleteAccount(index) {
			// 添加防抖，避免频繁操作
			if (this.deleteAccountTimer) {
				clearTimeout(this.deleteAccountTimer);
			}
			
			this.deleteAccountTimer = setTimeout(() => {
				uni.showModal({
					title: '确认删除',
					content: '确定要删除该账号吗？删除后将清除该账号的所有配置数据。',
					success: (res) => {
						if (res.confirm) {
							const account = this.accounts[index];
							
							// 如果删除的是当前账号，需要清除相关配置
							if (this.currentAccount?.roleId === account.roleId) {
								// 清除当前账号的配置
								const currentConfig = uni.getStorageSync('plunder_config');
								if (currentConfig && currentConfig.roleId === account.roleId) {
									// 清除配置
									uni.removeStorageSync('plunder_config');
									// 发送配置更新事件，通知其他页面清除数据
									uni.$emit('config-updated', null);
								}
								
								// 清除运行状态
								uni.removeStorageSync('plunder_running');
								// 发送状态更新事件
								uni.$emit('globalStateChange', { key: 'isRunning', value: false });
								
								// 清除其他相关数据
								uni.removeStorageSync('mine_rank_list');
								uni.removeStorageSync('mine_rank_query_state');
								uni.removeStorageSync('mine_owner_list');
								
								if (this.accounts.length > 0) {
									// 使用 nextTick 确保状态更新后再切换账号
									this.$nextTick(() => {
										this.switchAccount(this.accounts[0]);
									});
								} else {
									this.currentAccount = null;
									uni.removeStorageSync('current_account_id');
								}
							}
							
							// 从账号列表中删除
							this.accounts.splice(index, 1);
							
							// 保存更新后的账号列表
							uni.setStorageSync('plunder_accounts', this.accounts);
							
							uni.showToast({
								title: '删除成功',
								icon: 'success'
							});
							
							// 发送账号更新事件
							uni.$emit('accounts-updated', this.accounts);
						}
					}
				});
			}, 300); // 300ms 的防抖延迟
		},
		
		// 添加新账号
		addNewAccount(accountData) {
			// 添加防抖，避免频繁添加
			if (this.addAccountTimer) {
				clearTimeout(this.addAccountTimer);
			}
			
			this.addAccountTimer = setTimeout(() => {
				// 检查是否已存在相同roleId的账号
				const existingIndex = this.accounts.findIndex(acc => acc.roleId === accountData.roleId);
				if (existingIndex !== -1) {
					// 更新已存在的账号
					this.accounts[existingIndex] = {
						...this.accounts[existingIndex],
						...accountData
					};
				} else {
					// 添加新账号
					this.accounts.push(accountData);
				}
				
				// 保存账号列表
				uni.setStorageSync('plunder_accounts', this.accounts);
				
				// 如果是第一个账号，自动设置为当前账号
				if (!this.currentAccount) {
					// 使用 nextTick 确保状态更新后再切换账号
					this.$nextTick(() => {
						this.switchAccount(accountData);
					});
				}
			}, 300); // 300ms 的防抖延迟
		},
		
		getWxLoginQrCode() {
			this.showLoginArea = true;
			const that = this;
			
			if (that.hasValidToken) {
				uni.showToast({
					title: '已获取到Token',
					icon: 'none'
				});
				return;
			}
			
			if (that.isGettingQrCode) {
				return;
			}
			
			that.isGettingQrCode = true;
			that.scanStatus = '正在获取二维码...';
			
			if (that.scanTimer) {
				clearInterval(that.scanTimer);
				that.scanTimer = null;
			}
			
			uni.request({
				url: 'https://open.weixin.qq.com/connect/app/qrconnect',
				data: that.wxLoginParams,
				header: that.wxLoginHeaders,
				method: 'GET',
				dataType: 'text',
				success: (res) => {
					console.log('获取UUID响应类型:', typeof res.data);
					
					if (res.statusCode === 200 && res.data) {
						const uuidPattern = /uuid:\s*"([^"]+)"/;
						const uuidMatch = uuidPattern.exec(res.data);
						
						if (uuidMatch && uuidMatch[1]) {
							that.uuid = uuidMatch[1];
							console.log('提取的UUID:', that.uuid);
							that.getQrCodeImage(that.uuid);
						} else {
							that.scanStatus = '未能获取UUID';
							uni.showToast({
								title: '未能获取UUID',
								icon: 'none'
							});
							console.error('未找到UUID，响应内容:', res.data.substring(0, 200));
							that.isGettingQrCode = false;
						}
					} else {
						that.scanStatus = '请求失败';
						uni.showToast({
							title: '请求失败',
							icon: 'none'
						});
						that.isGettingQrCode = false;
					}
				},
				fail: (err) => {
					that.scanStatus = '网络请求失败';
					console.error('请求失败:', err);
					uni.showToast({
						title: '网络请求失败',
						icon: 'none'
					});
					that.isGettingQrCode = false;
				}
			});
		},
		getQrCodeImage(uuid) {
			const that = this;
			const qrUrl = `https://open.weixin.qq.com/connect/qrcode/${uuid}`;
			that.scanStatus = '正在加载二维码...';
			
			uni.request({
				url: qrUrl,
				header: {
					"User-Agent": "Mozilla/5.0", 
					"Accept": "*/*",
					"Connection": "keep-alive"
				},
				method: 'GET',
				responseType: 'arraybuffer',
				success: (res) => {
					console.log('获取二维码响应状态:', res.statusCode);
					if (res.statusCode === 200 && res.data) {
						const base64 = uni.arrayBufferToBase64(res.data);
						that.qrCodePath = 'data:image/png;base64,' + base64;
						that.scanStatus = '请使用微信扫描二维码';
						
						uni.showToast({
							title: '二维码获取成功',
							icon: 'success'
						});
						
						setTimeout(() => {
							that.startCheckScanStatus();
							that.isGettingQrCode = false;
						}, 2000);
					} else {
						that.scanStatus = '获取二维码失败';
						uni.showToast({
							title: '获取二维码失败',
							icon: 'none'
						});
						that.isGettingQrCode = false;
					}
				},
				fail: (err) => {
					that.scanStatus = '获取二维码失败';
					console.error('获取二维码失败:', err);
					uni.showToast({
						title: '获取二维码失败',
						icon: 'none'
					});
					that.isGettingQrCode = false;
				}
			});
		},
		startCheckScanStatus() {
			const that = this;
			if (!that.uuid) return;
			
			if (that.scanTimer) {
				clearInterval(that.scanTimer);
			}
			
			that.scanStatus = '开始检测扫码状态...';
			console.log('开始检测扫码状态，UUID:', that.uuid);
			
			that.checkScanStatus();
			
			that.scanTimer = setInterval(() => {
				that.checkScanStatus();
			}, 2000);
		},
		checkScanStatus() {
			const that = this;
			const timeNow = Date.now();
			const url = `https://long.open.weixin.qq.com/connect/l/qrconnect?uuid=${that.uuid}&f=url&_=${timeNow}`;
			
			uni.request({
				url: url,
				method: 'GET',
				dataType: 'text',
				success: (res) => {
					console.log('扫码状态检查原始响应:', res.data);
					
					if (res.statusCode === 200 && res.data) {
						const errcodePattern = /window\.wx_errcode=(\d+);/;
						const errcodeMatch = errcodePattern.exec(res.data);
						
						if (errcodeMatch) {
							const errcode = errcodeMatch[1];
							console.log('扫码状态码:', errcode);
							
							if (errcode === '408') {
								that.scanStatus = '等待扫码中...';
							} else if (errcode === '404') {
								that.scanStatus = '等待扫码中...';
							} else if (errcode === '403') {
								that.scanStatus = '用户已取消授权';
							} else if (errcode === '405') {
								that.scanStatus = '扫码成功，正在获取授权...';
								
								const redirectPattern = /window\.wx_redirecturl='([^']+)'/;
								const redirectMatch = redirectPattern.exec(res.data);
								
								if (redirectMatch) {
									const redirectUrl = decodeURIComponent(redirectMatch[1]);
									console.log('获取到重定向URL:', redirectUrl);
									
									const codePattern = /code=([^&]+)/;
									const codeMatch = codePattern.exec(redirectUrl);
									
									if (codeMatch) {
										const code = codeMatch[1];
										console.log('获取到授权码:', code);
										that.scanStatus = '授权成功，正在获取Token...';
										
										that.getChaojiToken(code);
										
										clearInterval(that.scanTimer);
									} else {
										console.error('未能从重定向URL中提取code:', redirectUrl);
										that.scanStatus = '未能获取授权码';
									}
								} else {
									console.error('未能提取重定向URL');
									that.scanStatus = '未能获取重定向URL';
								}
							}
						} else {
							console.error('未能提取错误码');
							that.scanStatus = '未能识别扫码状态';
						}
					}
				},
				fail: (err) => {
					console.error('检查扫码状态失败:', err);
					that.scanStatus = '检查扫码状态失败';
				}
			});
		},
		getChaojiToken(code) {
			const that = this;
			that.scanStatus = '正在获取超级链接Token...';
			console.log('开始获取超级链接Token，授权码:', code);
			
			uni.request({
				url: 'https://super-link-api.lucklyworld.com/api/auth/wx',
				method: 'POST',
				header: {
					'User-Agent': 'com.yiqun.superlink/2.3.7-official Dalvik/2.1.0 (Linux; U; Android 11; RMX1925 Build/RQ3A.231116.156)',
					'Accept-Encoding': 'UTF-8',
					'Accept': '*/*',
					'Connection': 'Keep-Alive',
					'Host': 'super-link-api.lucklyworld.com',
					'packageid': 'com.yiqun.superlink',
					'version': '2.3.7',
					'Channel': 'official',
					'androidid': 'c7dbbd8e6dfcb854',
					'userId': '',
					'uid': '',
					'IMEI': '229276238834486',
					'oaid': '',
					'test-encrypt': '0',
					'content-type': 'application/x-www-form-urlencoded'
				},
				data: {
					'code': code,
					'credential': code,
					'deviceName': 'RMX1925'
				},
				success: (res) => {
					console.log('获取超级链接token完整响应:', res);
					
					if (res.statusCode === 200 && res.data) {
						console.log('超级链接token响应数据:', res.data);
						
						if (res.data.token) {
							that.chaojiToken = res.data.token;
							that.scanStatus = '超级链接Token获取成功，正在获取潮玩宇宙Token...';
							
							uni.setStorageSync('chaojiToken', that.chaojiToken);
							
							that.getChaowanToken(that.chaojiToken);
						} else {
							console.error('响应中没有token字段:', res.data);
							that.scanStatus = '获取超级链接Token失败: 响应中没有token';
						}
					} else {
						console.error('获取超级链接token失败，状态码:', res.statusCode);
						that.scanStatus = '获取超级链接Token失败: ' + (res.statusCode || '未知错误');
					}
				},
				fail: (err) => {
					console.error('获取超级链接token请求失败:', err);
					that.scanStatus = '获取超级链接Token请求失败';
				}
			});
		},
		getChaowanToken(chaojiToken) {
			const that = this;
			uni.request({
				url: 'https://super-link-api.lucklyworld.com/v9/api/super/boxes/authorize',
				method: 'POST',
				header: {
					'User-Agent': 'com.yiqun.superlink/4.0.5-official Dalvik/2.1.0 (Linux; U; Android 12; SM-A5260 Build/a5031fa.0)',
					'Connection': 'Keep-Alive',
					'Accept-Encoding': 'UTF-8',
					'packageId': 'com.yiqun.superlink',
					'version': '4.0.5',
					'channel': 'official',
					'deviceId': '1198f8ab17347a5bef5c9389d26dce42c83256dc',
					'androidId': 'aad524da0eb63537',
					'userId': '2861576',
					'token': chaojiToken,
					'IMEI': '',
					'Content-Type': 'application/json'
				},
				data: {
					'clientId': '08729c570ebd81df2f377ed7354a165c',
					'state': '',
					'scope': '',
					'platform': 'android',
					'packageName': 'com.caike.lomo',
					'packageSign': '16e32175430a994a35b210d92fc9e4d2fa8ebb44'
				},
				success: (res) => {
					console.log('获取授权码响应:', res.data);
					if (res.statusCode === 200 && res.data && res.data.code) {
						const code = res.data.code;
						that.scanStatus = '授权码获取成功，等待2秒后获取潮玩Token...';
						console.log('获取到的授权码:', code);
						
						setTimeout(() => {
							uni.request({
								url: 'https://android-api.lucklyworld.com/api/auth/link',
								method: 'POST',
								header: {
									'User-Agent': 'com.caike.lomo/4.3.5 (Linux; U; Android 12; zh-cn) (official; 403005)',
									'Connection': 'Keep-Alive',
									'Accept-Encoding': 'UTF-8',
									'Channel': 'official',
									'DEVICEID': '',
									'ANDROIDID': 'b72326e6151cf469',
									'oaid': '',
									'IMEI': '',
									'test-encrypt': '0',
									'Content-Type': 'application/json',
									'Accept': 'application/json'
								},
								data: {
									'code': code,
									'deviceName': 'Samsung SM-A5260',
									'platform': 'android',
									'version': '4.3.5'
								},
								success: (res2) => {
									console.log('获取潮玩token原始响应:', res2);
									
									if (res2.statusCode === 200) {
										let responseData = res2.data;
										console.log('响应数据:', responseData);
										
										try {
											if (typeof responseData === 'string') {
												responseData = JSON.parse(responseData);
											}
											
											if (responseData && responseData.token) {
												that.chaowanToken = responseData.token;
												that.userId = responseData.userId || '';
												that.scanStatus = '潮玩Token获取成功，正在获取修仙ID...';
												that.hasValidToken = true;
												
												uni.setStorageSync('chaowanToken', that.chaowanToken);
												uni.setStorageSync('chaowanUserId', that.userId);
												
												// 获取到Token和userId后，立即获取修仙ID
												that.getRoleId(that.chaowanToken, that.userId);
												
												if (that.scanTimer) {
													clearInterval(that.scanTimer);
													that.scanTimer = null;
												}
												
												// 更新状态
												that.roleId = responseData.roleId?.toString();
												that.scanStatus = '修仙ID获取成功';
												
												// 不在这里显示登录成功提示，让 getRoleId 处理
												
												// 使用 nextTick 确保状态更新后再跳转
												that.$nextTick(() => {
													setTimeout(() => {
														uni.switchTab({
															url: '/pages/attack/index',
															success: () => {
																console.log('跳转到设置页面成功');
															},
															fail: (err) => {
																console.error('跳转到设置页面失败:', err);
																uni.showToast({
																	title: '跳转失败',
																	icon: 'none'
																});
															}
														});
													}, 1500);
												});
												
												return responseData.roleId?.toString();
											} else {
												console.error('响应中没有token字段:', responseData);
												that.scanStatus = '获取潮玩Token失败: 响应中没有token';
												uni.showToast({
													title: '获取潮玩Token失败',
													icon: 'none'
												});
											}
										} catch (e) {
											console.error('解析响应数据失败:', e);
											that.scanStatus = '获取潮玩Token失败: ' + e.message;
											uni.showToast({
												title: '获取潮玩Token失败',
												icon: 'none'
											});
										}
									} else {
										console.error('请求失败，状态码:', res2.statusCode);
										console.error('错误响应:', res2.data);
										that.scanStatus = '获取潮玩Token失败: ' + (res2.data?.message || '请求失败');
										uni.showToast({
											title: '获取潮玩Token失败',
											icon: 'none'
										});
									}
								},
								fail: (err) => {
									console.error('获取潮玩token失败:', err);
									that.scanStatus = '获取潮玩Token失败: ' + (err.errMsg || '请求失败');
									uni.showToast({
										title: '获取潮玩Token失败',
										icon: 'none'
									});
								}
							});
						}, 2000);
					} else {
						console.error('获取授权码失败，响应:', res.data);
						that.scanStatus = '获取授权码失败: ' + (res.data?.message || '未知错误');
						uni.showToast({
							title: '获取授权码失败',
							icon: 'none'
						});
					}
				},
				fail: (err) => {
					console.error('获取授权码失败:', err);
					that.scanStatus = '获取授权码失败: ' + (err.errMsg || '请求失败');
					uni.showToast({
						title: '获取授权码失败',
						icon: 'none'
					});
				}
			});
		},
		getRoleId: async function(token, uid) {
			try {
				// 添加防抖，避免频繁请求
				if (this.getRoleIdTimer) {
					clearTimeout(this.getRoleIdTimer);
				}
				
				return new Promise((resolve, reject) => {
					this.getRoleIdTimer = setTimeout(async () => {
						try {
							console.log('完整token:', token);
							console.log('开始获取修仙ID...', {
								token: token?.substring(0, 10) + '...',
								tokenLength: token?.length,
								uid
							});
							
							// 先检查token和uid是否有效
							if (!token || !uid) {
								throw new Error(`无效的参数: token=${!!token}, uid=${!!uid}`);
							}
							
							// 先获取用户信息
							const response = await uni.request({
								url: `https://farm-api.lucklyworld.com/v8/api/user/home`,
								method: 'POST',
								header: {
									'Content-Type': 'application/json',
									'Accept': 'application/json',
									'token': token,
									'User-Agent': 'com.caike.lomo/4.2.6 (Linux; U; Android 12; zh-cn) (91416; 402060)bbcbce6e97449754',
									'Channel': 'official',
									'DEVICEID': '',
									'ANDROIDID': 'a7b19730952f1068',
									'oaid': '',
									'IMEI': '352746026192015',
									'test-encrypt': '0',
									'uid': uid,
									'Connection': 'Keep-Alive',
									'Accept-Encoding': 'identity'  // 不使用gzip压缩
								},
								data: {
									uid: uid,
									version: '2.0.4'
								}
							});

							console.log('获取修仙ID完整响应:', {
								statusCode: response.statusCode,
								header: response.header,
								requestUrl: response.config?.url,
								requestMethod: response.config?.method,
								data: response.data
							});
							
							if (response.statusCode === 200 && response.data) {
								try {
									// 尝试解析JSON
									const responseData = typeof response.data === 'string' ? JSON.parse(response.data) : response.data;
									console.log('解析后的响应数据:', responseData);
									
									// 检查响应数据结构
									if (responseData.errorCode !== undefined && responseData.errorCode !== 0) {
										throw new Error(`API返回错误: ${responseData.message || '未知错误'}`);
									}
									
									// 从用户信息中获取roleId和nickname
									const roleId = responseData.roleId?.toString();
									// 从不同可能的位置获取nickname
									const nickname = responseData.nickname || 
												   responseData.data?.nickname || 
												   responseData.userInfo?.nickname || 
												   responseData.user?.nickname || 
												   '未设置昵称';
									
									console.log('获取到的用户信息:', {
										roleId,
										nickname,
										rawData: responseData
									});
									
									if (roleId) {
										console.log('成功获取修仙ID:', roleId);
										
										// 保存账号信息
										const accountData = {
											token,
											uid,
											roleId,
											nickname,
											lastLogin: new Date().toISOString()
										};
										
										// 先保存账号信息
										this.addNewAccount(accountData);
										
										// 更新配置
										const configToSave = {
											token,
											uid,
											roleId,
											nickname,
											threshold: '168.0',
											quickRefreshCount: '3',
											quickRefreshDuration: '40',
											quickRefreshInterval: '4',
											nicknames: []
										};
										
										// 确保配置保存完成
										try {
											uni.setStorageSync('plunder_config', configToSave);
											console.log('配置保存成功，准备跳转');
											
											// 更新状态
											this.roleId = roleId;
											this.scanStatus = '修仙ID获取成功';
											
											// 显示登录成功提示
											this.showLoginSuccessToast();
											
											// 使用 nextTick 确保状态更新后再跳转
											this.$nextTick(() => {
												// 延迟跳转，确保存储操作完成
												setTimeout(() => {
													// 先发送配置更新事件
													uni.$emit('config-updated', configToSave);
													
													// 然后再跳转
													uni.switchTab({
														url: '/pages/attack/index',
														success: () => {
															console.log('跳转到设置页面成功，配置已更新');
															resolve(roleId);
														},
														fail: (err) => {
															console.error('跳转到设置页面失败:', err);
															uni.showToast({
																title: '跳转失败',
																icon: 'none'
															});
															reject(err);
														}
													});
												}, 500); // 减少延迟时间到500ms
											});
										} catch (error) {
											console.error('保存配置失败:', error);
											uni.showToast({
												title: '保存配置失败',
												icon: 'none'
											});
											reject(error);
										}
										
										return roleId;
									} else {
										throw new Error('未能从响应中获取修仙ID');
									}
								} catch (parseError) {
									console.error('解析响应数据失败:', parseError);
									throw new Error(`解析响应数据失败: ${parseError.message}`);
								}
							} else {
								throw new Error(`请求失败: 状态码=${response.statusCode}`);
							}
						} catch (error) {
							console.error('获取修仙ID失败，详细错误:', {
								message: error.message,
								stack: error.stack,
								response: error.response
							});
							this.scanStatus = `获取修仙ID失败: ${error.message}`;
							uni.showToast({
								title: `获取修仙ID失败: ${error.message}`,
								icon: 'none',
								duration: 3000
							});
							throw error;
						}
					}, 300); // 300ms 的防抖延迟
				});
			} catch (error) {
				console.error('获取修仙ID失败，详细错误:', {
					message: error.message,
					stack: error.stack,
					response: error.response
				});
				this.scanStatus = `获取修仙ID失败: ${error.message}`;
				uni.showToast({
					title: `获取修仙ID失败: ${error.message}`,
					icon: 'none',
					duration: 3000
				});
				throw error;
			}
		},
		copyToken(tokenType) {
			const token = this[tokenType];
			if (!token) return;
			
			uni.setClipboardData({
				data: token,
				success: () => {
					uni.showToast({
						title: '复制成功',
						icon: 'success'
					});
				}
			});
		},
		// 处理账号更新事件
		handleAccountsUpdate(updatedAccounts) {
			console.log('收到账号更新事件:', updatedAccounts);
			this.accounts = updatedAccounts;
			
			// 如果当前账号被更新，更新当前账号信息
			if (this.currentAccount) {
				const updatedCurrentAccount = updatedAccounts.find(acc => acc.roleId === this.currentAccount.roleId);
				if (updatedCurrentAccount) {
					this.currentAccount = updatedCurrentAccount;
				}
			}
			
			// 如果没有当前账号但有账号列表，选择第一个账号
			if (!this.currentAccount && updatedAccounts.length > 0) {
				this.$nextTick(() => {
					this.switchAccount(updatedAccounts[0]);
				});
			}
		},
		// 关闭登录区域
		closeLoginArea() {
			this.showLoginArea = false;
			this.qrCodePath = '';
			this.scanStatus = '';
			if (this.scanTimer) {
				clearInterval(this.scanTimer);
				this.scanTimer = null;
			}
			this.isGettingQrCode = false;
		},
		// 修改登录成功提示方法
		showLoginSuccessToast() {
			// 如果已经显示过提示，直接返回
			if (this.hasShownLoginToast) {
				return;
			}
			
			const lastLoginTime = uni.getStorageSync('last_login_time');
			const now = Date.now();
			const isFirstLogin = !lastLoginTime;
			const isReLogin = lastLoginTime && (now - lastLoginTime > 24 * 60 * 60 * 1000);
			
			if (isFirstLogin || isReLogin) {
				uni.showToast({
					title: '登录成功',
					icon: 'success'
				});
				// 设置标志位
				this.hasShownLoginToast = true;
			}
			
			// 更新最后登录时间
			uni.setStorageSync('last_login_time', now);
		}
	},
	onLoad() {
		this.loadAccounts();
		// 监听账号更新事件
		uni.$on('accounts-updated', this.handleAccountsUpdate);
	},
	onShow() {
		this.loadAccounts();
	},
	onUnload() {
		// 清除所有定时器
		if (this.scanTimer) {
			clearInterval(this.scanTimer);
			this.scanTimer = null;
		}
		if (this.switchAccountTimer) {
			clearTimeout(this.switchAccountTimer);
			this.switchAccountTimer = null;
		}
		if (this.deleteAccountTimer) {
			clearTimeout(this.deleteAccountTimer);
			this.deleteAccountTimer = null;
		}
		if (this.addAccountTimer) {
			clearTimeout(this.addAccountTimer);
			this.addAccountTimer = null;
		}
		if (this.getRoleIdTimer) {
			clearTimeout(this.getRoleIdTimer);
			this.getRoleIdTimer = null;
		}
		// 移除事件监听
		uni.$off('accounts-updated', this.handleAccountsUpdate);
		// 在组件卸载时重置标志位
		this.hasShownLoginToast = false;
	}
}
</script>

<style>
.container {
	padding: 24rpx;
	/* 移除广告栏相关的padding */
	padding-top: 24rpx;
	min-height: 100vh;
	background: linear-gradient(135deg, #f5f7fa 0%, #e4e7eb 100%);
}

/* 移除广告栏相关样式 */
.ad-banner-container,
.ad-banner {
	display: none;
}

.account-manager {
	width: 100%;
	max-width: 750rpx;
	background-color: #ffffff;
	border-radius: 12rpx;
	padding: 16rpx 20rpx;
	margin-bottom: 20rpx;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.account-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 16rpx;
}

.account-title {
	font-size: 28rpx;
	font-weight: 600;
	color: #333;
}

.add-account-btn {
	background: linear-gradient(135deg, #4CAF50 0%, #45a049 100%);
	color: #FFFFFF;
	font-size: 24rpx;
	padding: 8rpx 20rpx;
	border-radius: 6rpx;
	height: 48rpx;
	min-width: 120rpx;
	display: inline-flex;
	align-items: center;
	justify-content: center;
	border: none;
	box-shadow: 0 2rpx 6rpx rgba(76, 175, 80, 0.2);
}

.account-list {
	display: flex;
	flex-direction: column;
	gap: 12rpx;
}

.account-item {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 12rpx 16rpx;
	background-color: #f8f8f8;
	border-radius: 8rpx;
	border: 1rpx solid transparent;
	transition: all 0.3s ease;
}

.account-item.account-active {
	border-color: #4CAF50;
	background-color: rgba(76, 175, 80, 0.05);
}

.account-info {
	flex: 1;
	min-width: 0;
}

.account-nickname {
	font-size: 26rpx;
	font-weight: 600;
	color: #333;
	margin-bottom: 4rpx;
	display: block;
	white-space: nowrap;
	overflow: hidden;
	text-overflow: ellipsis;
}

.account-id {
	font-size: 22rpx;
	color: #666;
}

.account-actions {
	display: flex;
	gap: 8rpx;
}

.account-btn {
	font-size: 22rpx;
	padding: 6rpx 16rpx;
	border-radius: 4rpx;
	height: 40rpx;
	min-width: 80rpx;
	display: inline-flex;
	align-items: center;
	justify-content: center;
	background: linear-gradient(135deg, #4CAF50 0%, #45a049 100%);
	color: #FFFFFF;
	border: none;
	box-shadow: 0 2rpx 4rpx rgba(76, 175, 80, 0.2);
}

.account-btn.delete {
	background: linear-gradient(135deg, #f44336 0%, #e53935 100%);
	box-shadow: 0 2rpx 4rpx rgba(244, 67, 54, 0.2);
}

.wx-login-area {
	width: 100%;
	max-width: 750rpx;
	display: flex;
	flex-direction: column;
	align-items: center;
	background-color: #ffffff;
	border-radius: 12rpx;
	padding: 20rpx;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.wx-login-header {
	display: flex;
	justify-content: center;
	align-items: center;
	position: relative;
	width: 100%;
	margin-bottom: 20rpx;
}

.wx-login-btn {
	background: linear-gradient(135deg, #4CAF50 0%, #45a049 100%);
	color: #FFFFFF;
	font-size: 24rpx;
	padding: 8rpx 20rpx;
	border-radius: 6rpx;
	height: 48rpx;
	min-width: 240rpx;
	display: inline-flex;
	align-items: center;
	justify-content: center;
	border: none;
	box-shadow: 0 2rpx 6rpx rgba(76, 175, 80, 0.2);
	margin-bottom: 20rpx;
}

.close-btn {
	position: absolute;
	right: 0;
	top: 50%;
	transform: translateY(-50%);
	width: 48rpx;
	height: 48rpx;
	min-width: 48rpx;
	padding: 0;
	display: flex;
	align-items: center;
	justify-content: center;
	background: #f5f5f5;
	color: #666;
	font-size: 28rpx;
	border-radius: 50%;
	border: none;
	box-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.1);
	transition: all 0.3s ease;
}

.close-btn:active {
	background: #e0e0e0;
	transform: translateY(-50%) scale(0.95);
}

.qr-code {
	width: 360rpx;
	height: 360rpx;
	margin: 16rpx 0;
	border-radius: 8rpx;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.qr-tip {
	font-size: 24rpx;
	color: #666666;
	margin-top: 12rpx;
} 

.scan-status {
	font-size: 24rpx;
	color: #333333;
	margin-top: 12rpx;
	font-weight: 500;
	padding: 8rpx 16rpx;
	background: rgba(0, 0, 0, 0.03);
	border-radius: 6rpx;
}

/* 响应式调整 */
@media screen and (min-width: 768px) {
	.container {
		padding: 32rpx 24rpx;
	}
	
	.account-manager {
		padding: 20rpx 24rpx;
	}
	
	.account-title {
		font-size: 30rpx;
	}
	
	.add-account-btn {
		font-size: 26rpx;
		padding: 10rpx 24rpx;
		height: 52rpx;
	}
	
	.account-nickname {
		font-size: 28rpx;
	}
	
	.account-id {
		font-size: 24rpx;
	}
	
	.account-btn {
		font-size: 24rpx;
		padding: 8rpx 20rpx;
		height: 44rpx;
	}
	
	.wx-login-btn {
		font-size: 26rpx;
		padding: 10rpx 24rpx;
		height: 52rpx;
	}
	
	.qr-code {
		width: 400rpx;
		height: 400rpx;
	}
	
	.qr-tip,
	.scan-status {
		font-size: 26rpx;
	}
	
	.close-btn {
		width: 52rpx;
		height: 52rpx;
		min-width: 52rpx;
		font-size: 30rpx;
	}
}
</style>